package com.gao.mq.util;

import com.gao.mq.service.MessageConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    Logger logger = LoggerFactory.getLogger(MessageConsumerService.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 从左边插入数据
     * @param key
     * @param value
     * @return
     */
    public boolean leftPush(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 弹出右边的值
     *
     * @param key
     */
    public Object rightPop(String key) {
        //绑定操作
        return rightPop(key, 1000);
    }

    /**
     * 弹出右边的值
     *
     * @param key
     */
    public Object rightPop(String key, long time) {
        //绑定操作
        return rightPop(key, time, TimeUnit.SECONDS);
    }

    /**
     * 弹出右边的值
     *
     * @param key
     */
    public Object rightPop(String key, long time, TimeUnit timeUnit) {
        //绑定操作
        try {
            return redisTemplate.opsForList().rightPop(key, time, timeUnit);
        } catch (Exception e) {
            return null;
        }
    }
}
